<template>
    <div>
        <div v-if="mode === 'DESIGN'">
            <!--组件在设计器中的样子-->
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show" disabled>
                <template #append>
                    <el-button @click="show">{{$t('module.select')}}</el-button>
                </template>
            </el-input>
        </div>
        <div v-else-if="mode === 'PC' && !readonly">
            <!--组件在PC端预览及真实显示的样子-->
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show">
                <template #append>
                    <el-button @click="show">{{$t('module.select')}}</el-button>
                </template>
            </el-input>
        </div>
        <div v-else-if="mode === 'MOBILE' && !readonly">
            <!--组件在移动端预览及真实显示的样子-->
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show">
                <template #append>
                    <el-button @click="show">{{$t('module.select')}}</el-button>
                </template>
            </el-input>
        </div>
        <div v-else>
            <!--组件在流程实例预览中，只读状态下样子-->
            <el-input v-model="_value" :placeholder="$t(placeholder)" :disabled="readonly" @keyup.enter.native="show">
                <template #append>
                    <el-button @click="show">{{$t('module.select')}}</el-button>
                </template>
            </el-input>
        </div>
        <!-- 弹框选择数据 -->
        <w-dialog :title="$t('module.select')" width="70%" style="height:600px;max-height:950px;overflow:hidden;" v-model="visible"
            @ok="httpOk" show-cancel-button>
            <div class="dialog">
                <el-input v-model="keywordSelect" style="width: 100%;margin-bottom: 5px;" :placeholder="$t('module.keywordSearch')"
                    @change="search" />
                <el-table :data="tableData" style="height: 90%;width: 100%" border
                    :header-cell-style="{ color: '#000', fontWeight: 'bold' }" :cell-style="{ whiteSpace: 'pre-wrap' }"
                    @selection-change="handleSelectionChange" :row-key="getRowKey" ref="multipleTable">
                    <!-- 表格头循环 -->
                    <!-- @row-dblclick="rowClick" -->
                    <el-table-column type="selection" width="55" v-if="isMultiple == '是'"
                        :reserve-selection="true"></el-table-column>
                    <!-- 按照接口返回的key渲染 -->
                    <template v-for="(item, index) in headerDate" :key="index">
                        <el-table-column v-if="item.placeholder" :prop="item.value" :label="$t(item.placeholder)"
                            width="auto"></el-table-column>
                    </template>
                </el-table>
                <div class="demo-pagination-block" style="margin-top:10px">
                    <el-pagination :currentPage="currentPage" :page-size="pageSize" :page-sizes="[20, 50, 80]"
                        :small="small" :disabled="disabled" :background="background" pager-count="4"
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </w-dialog>
    </div>
</template>

<script>
//混入配置
import componentMinxins from '../ComponentMinxins'
import store from "@/store/index.js";
export default {
    mixins: [componentMinxins],
    name: "TextRowSelector",
    components: {},
    props: {
        index: {
            type: Number,
            default: 0,
        },
        modelValue: {
            type: String,
        },
        placeholder: {
            type: String,
            default: 'webAuto.selectOption',
        },
        expanding: {
            type: Boolean,
            default: false,
        },
        dataSource: {
            type: String,
            default: '',
        },
        isMultiple: {
            type: String,
            default: '是',
        },
        tables: {
            type: String,
            default: ''
        },
        optionText: {
            type: Array,
            default: () => {
                return []
            }
        },
        formData: {
            type: Object,
            default: () => {
                return {}
            }
        },
        http: {
            type: Object,
            default: () => {
                return {
                    url: null,
                    method: 'GET',
                    headers: [],
                    contentType: 'JSON',
                    params: [],
                    data: null,
                    preHandler: null,
                    aftHandler: {
                        isJs: false,
                        js: '',
                        rule: {
                            source: '',
                            name: '',
                            value: ''
                        }
                    },
                }
            }
        }
    },
    data() {
        return {
            loading: false,
            visible: false,
            keywordSelect: '',
            headerDate: [],
            tableData: [], // 表格绑定数据
            pageSize: 15, // 分页的
            total: 0,
            currentPage: 1,
            rowLis: [], // 选择行的数据
            small: false,
            background: false,
            preHandlerFuc: null,
            aftHandlerFuc: null,
            disabled: false,
            lineNo: '',
        }
    },
    computed: {
        _value: {
            get() {
                return this.modelValue
            },
            set(val) {
                this.$emit('update:modelValue', val)
            },
        },
        formItems(){
            return this.$store.state.design.formItems
        },
        formMap(){
            const map = new Map();
            this.itemToMap(this.formItems, map)
            return map
        },
    },
    mounted() {
        // 回显已选中的行
        this.$nextTick(() => {
            this.rowLis.forEach(row => {
                this.$refs.multipleTable.toggleRowSelection(row, true);
            });
        });
    },
    methods: {
        // 打开弹框
        show() {
            this.doRequest()
            this.visible = true
        },
        itemToMap(forms, map){
            forms.forEach(item => {
                if (item.name === 'TableList') {
                    map.set(item.id, item)
                    this.itemToMap(item.props.columns, map)
                } else if (item.name === 'SpanLayout') {
                    this.itemToMap(item.props.items, map)
                } else {
                    map.set(item.id, item)
                }
            })
        },
        // 多选
        handleSelectionChange(val) {
            this.rowLis = val
        },
        getRowKey(row) {
            return row.id; // 假设每行数据都有唯一的id字段
        },
        // 弹框点击确认
        httpOk() {
          if (this.rowLis == null || Object.keys(this.rowLis).length == 0) {
            this.$message.warning(this.$t('webAuto.selectDataFirst'))
            return
          } else {

            this.lineNo = this.index
            // 点击确定后进行赋值
            let _this = this

            let newObject = {};

            // 遍历 rowLis 数组
            this.rowLis.forEach(item => {
              Object.entries(item).forEach(([key, value]) => {
                // 如果 newObject 中还没有这个键，则初始化为当前值
                if (!newObject[key]) {
                  newObject[key] = value.toString();
                } else {
                  // 否则，将当前值拼接到已有的值后面
                  newObject[key] += ',' + value;
                }
              });
            });



            // 遍历 optionText 数组
            this.optionText.forEach(item => {
              // 检查 newObject 中是否存在该键
              if (newObject.hasOwnProperty(item.value)&& item.name) {
                // 在 newObject 中新增一个键，键为 item.name，值为 newObject[item.value]
                newObject[item.name] = newObject[item.value];
              }
            });


            this.formData[this.tables][this.index-1] = {...this.formData[this.tables][this.index-1],...newObject}

            // let currentData = this.formData[this.tables];

            // // 过滤掉空值对象
            // let newArr = currentData?.filter(item => {
            //   // 检查每个对象的属性值
            //   return Object.values(item).some(value => {
            //     return value !== undefined && value !== 'undefined';
            //   });
            // });
            // // 将去掉空值后的结果重新赋值
            // this.formData[this.tables] = newArr;

            // console.log(this.optionText,'this.optionText')
            // console.log(this.formData,'this.formData')
            // console.log(newObject,'newObject')
            // console.log(this.lineNo,'this.lineNo')

            this.visible = false

          }

        },
        // 判断数组中包含某个不确定的对象
        containsObject(array, object) {
            return array.some(item => {
                for (let key in object) {
                    if (item[key] !== object[key]) {
                        return false;
                    }
                }
                return true;
            });
        },
         // id标识长度5位
         generateUniqueId(length = 5) {
            const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            const charactersLength = characters.length;
            for (let i = 0; i < length; i++) {
                result += characters.charAt(Math.floor(Math.random() * charactersLength));
            }
            return result;
        },
        doRequest() {
            this.headerDate = []
            if (this.http.url && this.http.method) {
                const params = {
                    url: this.http.url,
                    method: this.http.method.toLowerCase(),
                    headers: {
                        'Content-Type': this.http.contentType === 'JSON' ? 'application/json' : 'application/x-www-form-urlencoded',
                        ...this.coverParams(this.http.headers || [])
                    },
                    formData: Object.assign({}, this.formData),
                    params: this.coverParams(this.http.params || []), //查询条件
                    data: this.http.contentType === 'JSON' ? JSON.parse(this.bindVar(this.http.data || '{}')) : ''
                }
                params.params.value = this.keywordSelect   //表格自定义的查询条件 关键字查询
                params.params.pageSize = this.pageSize //分页 第几页
                params.params.pageNo = this.currentPage  //分页 每页条数
                this.preHandler(params, this.http.preHandler)
                //这里由于前置处理后，可能修改params参数，所以需要重新处理
                if (this.http.contentType !== 'JSON') {
                    params.data = this.coverParams(params.params, true)
                    params.params = {} //去除参数，防止参数跑到url中
                }
                this.loading = true
                this.$axios.request(params).then(rsp => {
                    // 接口返回数据赋值给表格，自定义处理了，就没有后置处理
                    // console.log(this.options)
                    // 循环比对表格表头
                    let arr = Object.keys(rsp.data.model)
                    this.optionText.forEach(item => {
                        arr.forEach(name => {
                            if (name === item.value) {
                                this.headerDate.push(item)
                            }
                        })
                    })
                    rsp.data.data.forEach(item => {
                        item.selection = false
                        item.id=this.generateUniqueId()
                    })
                    this.tableData = rsp.data.data

                    this.total = rsp.data.total
                }).catch(err => {
                    this.loading = false
                    this.$message.warning(this.$t('webAuto.RequestSource') + JSON.stringify(err))
                })
            }
        },
        //前置处理
        preHandler(params, script) {
            if (!this.preHandlerFuc) {
                this.preHandlerFuc = new Function('ctx', `${script}\n preHandler(ctx)`)
            }
            try {
                this.preHandlerFuc(params)
            } catch (e) {
                // console.log(e)
            }
        },
        bindVar(str) {
            return str.replace(/\$\{(\w+)\}/g, (match, key) => {
                return this.formData[key] || '';
            })
        },
        //数组转对象
        coverParams(args, isForm = false) {
            let params = {};
            if (Array.isArray(args)) {
                args.forEach(arg => {
                    if (this.$isNotEmpty(arg.name)) {
                        params[arg.name] = arg.value.replace(/\$\{(\w+)\}/g, (match, key) => {
                            // 特殊处理 ${lang}
                            if (key === 'lang') {
                              return localStorage.getItem('lang')?.includes('中文') ? 'zh-CN' : localStorage.getItem('lang')?.includes('English')?'en-US':'es-MX';
                            }
                            return this.formData[key] || '';
                        })
                    }
                })
            } else {
                params = { ...args }
            }
            if (isForm) {
                return Object.keys(params).map(v => `${encodeURIComponent(v)}=${encodeURIComponent(params[v])}`).join('&')
            }
            return params
        },
        // 弹框里面表格的查询
        search() {
            this.doRequest()
        },
        // 分页相关函数
        handleSizeChange(val) {
            this.pageSize = val
            this.doRequest()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.doRequest()
        }
    }

}
</script>

<style scoped>
.demo-pagination-block {
    height: 40px;
    width: 100%;
    margin-top: 8px;
    box-sizing: border-box;
    font-size: 12px;
    background-color: #faf8f8;
    overflow: hidden;
}

.dialog {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 500px;
}

.el-select .el-select--default {
    width: 100px !important;
}

::v-deep .el-table__body tr.current-row>td {
    color: #fff;
    background: #e69346 !important;
}
</style>
